package com.iplatform.iplatformuser.privilege.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iplatform.commons.pagination.Pagination;
import com.iplatform.commons.utils.CommResponse;
import com.iplatform.commons.utils.UserUtil;
import com.iplatform.iplatformuser.framework.springmvc.BaseController;
import com.iplatform.iplatformuser.function.group.service.inter.IPriGroupService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriMenuService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriOrganizationService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriRoleService;
import com.iplatform.iplatformuser.privilege.service.inter.ITargetService;
import com.iplatform.module.privilege.PriManagerBean;
import com.iplatform.module.privilege.PriMenuBean;
import com.iplatform.module.privilege.PriRoleBean;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 *
 * @author ld
 */
@RestController
@RequestMapping("/api/v1/role")
@Api(tags = "角色管理接口")
public class ApiPriRoleController extends BaseController {

    @Autowired
    public IPriRoleService userRoleService;

    @Autowired
    public IPriOrganizationService priOrganizationService;

    @Autowired
    public IPriMenuService priMenuService;

    @Autowired
    public ITargetService targetService;

    @Autowired
    public IPriGroupService groupService;

    /**
     * 角色列表
     *
     * @param formMap
     * @param pagination
     * @return
     */
    @ApiOperation(value = "角色列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleName", value = "名称", required = false, paramType = "query"),})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @GetMapping(value = "/list")
    public ResponseEntity<PageInfo<PriRoleBean>> list(
            @ApiParam(hidden = true) @RequestParam Map<String, String> formMap,
            @ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {

        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        List<PriRoleBean> resultList = userRoleService.loadRole(formMap);
        PageInfo<PriRoleBean> pageInfo = new PageInfo<PriRoleBean>(resultList);

        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }


    /**
     * 角色详情
     *
     * @param formMap
     * @return
     */
    @ApiOperation(value = "角色详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "ID", required = true, paramType = "path")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @GetMapping(value = "/{roleId}")
    public ResponseEntity<PriRoleBean> detail(
            @ApiParam(hidden = true) @PathVariable Map<String, String> formMap) {

        List<PriRoleBean> resultList = userRoleService.loadRole(formMap);
        if (resultList.size() > 0) {
            return new ResponseEntity<>(resultList.get(0), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(null, HttpStatus.OK);
        }

    }

    /**
     * 新增
     *
     * @param priRoleBean
     * @return
     */
    @ApiOperation(value = "新增")
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PostMapping()
    public ResponseEntity<CommResponse> add(@ApiParam(hidden = true) @ModelAttribute(value = "PriRoleBean") PriRoleBean priRoleBean) {
        //对角色code进行判重
        Integer RoleCodeNum = userRoleService.addCheck(priRoleBean.getRoleCode(), "");
        if (RoleCodeNum >= 1) {
            return new ResponseEntity<>(new CommResponse("角色编码重复", false), HttpStatus.BAD_REQUEST);
        }
        // TODO 获取当前用户
        PriManagerBean pri = UserUtil.getLoginAppUser();
        if (pri != null) {
            priRoleBean.setCreatedBy(pri.getUserCode());
        } else {
            priRoleBean.setCreatedBy("admin");
        }

        if (StringUtils.isBlank(priRoleBean.getStatus())) {
            priRoleBean.setStatus("N");
        }
        if (StringUtils.isBlank(priRoleBean.getIsDeleted())) {
            priRoleBean.setIsDeleted("N");
        }
        if (priRoleBean.getVersion() == null) {
            priRoleBean.setVersion(BigDecimal.valueOf(1));
        }
        userRoleService.insert(priRoleBean);

        return new ResponseEntity<>(new CommResponse("添加成功", true), HttpStatus.CREATED);
    }

    /**
     * 更新菜单
     *
     * @param priRoleBean
     * @return
     */
    @ApiOperation(value = "更新角色")
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping()
    public ResponseEntity<CommResponse> update(@ApiParam(hidden = true) @ModelAttribute(value = "PriRoleBean") PriRoleBean priRoleBean) {
        Integer RoleCodeNum = userRoleService.addCheck(priRoleBean.getRoleCode(), priRoleBean.getRoleId());
        if (RoleCodeNum >= 1) {
            return new ResponseEntity<>(new CommResponse("角色编码重复", false), HttpStatus.BAD_REQUEST);
        }
        PriManagerBean pri = UserUtil.getLoginAppUser();
        if (pri != null) {
            priRoleBean.setUpdatedBy(pri.getUserCode());
        } else {
            priRoleBean.setUpdatedBy("admin");
        }
        userRoleService.update(priRoleBean);

        return new ResponseEntity<>(new CommResponse("更新成功", true), HttpStatus.OK);
    }

    /**
     * 删除角色
     *
     * @return
     */
    @ApiOperation(value = "删除角色")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "deleteIds", value = "删除的ID集合，逗号分隔", required = true, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping(value = "/batchDel")
    public ResponseEntity<CommResponse> del(@RequestParam String deleteIds) {

        userRoleService.batchDelete(deleteIds.split(","));

        return new ResponseEntity<>(new CommResponse("删除成功", true), HttpStatus.NO_CONTENT);

    }

    /**
     * 更新角色状态
     *
     * @param roleId
     * @return
     */
    @ApiOperation(value = "更新角色状态")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "ID", required = true, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping(value = "/status")
    public ResponseEntity<CommResponse> updateStatus(@RequestParam String roleId) {

        userRoleService.setIsUse(roleId);

        return new ResponseEntity<>(new CommResponse("更新角色成功", true), HttpStatus.OK);

    }

    /**
     * 角色未选中的用户列表
     *
     * @param formMap
     * @param pagination
     * @return
     */
    @ApiOperation(value = "角色未选中的用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "userName", value = "用户名称", required = false, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @GetMapping(value = "/managerPageForOutRole")
    public ResponseEntity<PageInfo<PriManagerBean>> selectManagerPageForOutRole(
            @ApiParam(hidden = true) @RequestParam Map<String, String> formMap,
            @ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {

        // if (StringUtils.isEmpty(formMap.get("orgName"))) {
        // formMap.put("orgName", "省公司");
        // }

        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        List<PriManagerBean> resultList = userRoleService
                .querySelectManagerWithOutRoleId(formMap);
        PageInfo<PriManagerBean> pageInfo = new PageInfo<PriManagerBean>(resultList);

        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }

    /**
     * 角色已经选中对的用户列表
     *
     * @param formMap
     * @return
     */
    @ApiOperation(value = "角色已经选中的用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "userName", value = "用户名称", required = false, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @GetMapping(value = "/managerPageForInRole")
    public ResponseEntity<PageInfo<PriManagerBean>> selectManagerPageForInRole(
            @ApiParam(hidden = true) @RequestParam Map<String, String> formMap, @ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {
        // if (StringUtils.isEmpty(formMap.get("orgName"))) {
        // formMap.put("orgName", "省公司");
        // }
        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        List<PriManagerBean> resultList = userRoleService.querySelectManagerWithRoleId(formMap);
        PageInfo<PriManagerBean> pageInfo = new PageInfo<>(resultList);
        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }

    /**
     * 角色绑定用户
     *
     * @param roleId
     * @param checkedIds
     * @return
     */
    @ApiOperation(value = "角色绑定用户")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "checkedIds", value = "选中的ID集合，逗号分隔", required = true, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PostMapping(value = "/managerRole")
    public ResponseEntity<CommResponse> saveManagerRole(@RequestParam String roleId, @RequestParam String checkedIds) {
        // TODO 获取当前用户

        userRoleService.updateManagerRole(roleId, checkedIds, "admin", true);// priManager.getUserCode()

        return new ResponseEntity<>(new CommResponse("绑定用户成功", true), HttpStatus.CREATED);
    }

    @ApiOperation(value = "移除角色用户绑定")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "checkedIds", value = "选中的ID集合，逗号分隔", required = true, paramType = "query")
    })
    @DeleteMapping(value = "managerRole")
    public ResponseEntity<CommResponse> delManagerRole(@RequestParam String roleId,
                                                       @RequestParam String checkedIds) {
        userRoleService.delManagerRole(roleId, checkedIds, "admin");
        return new ResponseEntity<>(new CommResponse("移除角色用户绑定成功", true), HttpStatus.NO_CONTENT);
    }

    /**
     * 角色绑定菜单的菜单列表
     *
     * @return
     */
    @ApiOperation(value = "角色绑定菜单的菜单列表")
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", required = true, value = "角色id"),
            @ApiImplicitParam(name = "menuName", required = false, value = "模糊查询菜单名")
    })
    @GetMapping(value = "/menuListByRoleId")
    public ResponseEntity<PageInfo<PriMenuBean>> queryMenuListByLevel(String roleId, String menuName) {

        List<PriMenuBean> resultList = userRoleService.queryMenuListWithRoleId(roleId, menuName);
        PageInfo<PriMenuBean> pageInfo = new PageInfo(resultList);

        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }

//	/**
//	 * 角色绑定菜单的菜单列表
//	 * @return
//	 */
//	@ApiOperation(value = "角色绑定菜单的菜单列表")
//	@ApiImplicitParams({
//			@ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true, paramType = "query") })
//	@ApiResponses({})
//	@GetMapping(value = "/allOptByMenuIds")
//	public ResponseEntity<Object> queryAllOptByMenuIds(
//			@ApiParam(hidden = true) @RequestParam Map<String, String> formMap) {
//
//		List<Map<String, String>> optList = userRoleService.queryAllOptByMenuIds(formMap);
//
//		return new ResponseEntity<>(optList, HttpStatus.OK);
//	}


    /**
     * 查询角色名称
     *
     * @return
     */
    @ApiOperation(value = "查询角色名称")
    @GetMapping(value = "/roleNameList")
    public ResponseEntity<JSONObject> queryRoleNameList() {

        List<Map<String, String>> resultList = userRoleService.queryRoleName();

        JSONObject allObject = new JSONObject();
        JSONArray arrayName = new JSONArray();

        for (Map<String, String> nameList : resultList) {
            JSONObject objectName = new JSONObject();
            objectName.put("roleName", nameList.get("roleName"));
            arrayName.add(objectName);
        }
        allObject.put("name", arrayName);
        return new ResponseEntity<>(allObject, HttpStatus.OK);
    }

    @ApiOperation(value = "角色绑定菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(dataType = "String[]", name = "menuIds", value = "菜单id数组", required = true)
    })
    @PostMapping("/roleBindMenus")
    public ResponseEntity<CommResponse> roleBindMenus(@RequestParam String roleId,@RequestParam String[] menuIds) {
        if (StringUtils.isBlank(roleId)) {
            return new ResponseEntity<>(new CommResponse("请选择一个角色进行操作", false), HttpStatus.BAD_REQUEST);
        }

        userRoleService.roleBindMenus(roleId, menuIds, BigDecimal.valueOf(1));
        return new ResponseEntity<>(new CommResponse("绑定菜单成功", true), HttpStatus.CREATED);
    }

    @ApiOperation(value = "移除角色绑定菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(dataType = "String[]", name = "menuIds", value = "菜单id数组", required = true)
    })
    @DeleteMapping("/removeRoleBindMenus")
    public ResponseEntity<CommResponse> removeRoleBindMenus(@RequestParam String roleId,@RequestParam String[] menuIds) {
        if (StringUtils.isBlank(roleId)) {
            return new ResponseEntity<>(new CommResponse("请选择一个角色进行操作", false), HttpStatus.BAD_REQUEST);
        }
        userRoleService.removeBind(roleId, menuIds);
        return new ResponseEntity<>(new CommResponse("解除绑定成功", true), HttpStatus.CREATED);
    }

    /**
     * 角色列表(不分页)
     *
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "roleName", value = "名称", required = false, paramType = "query"),})
    @ApiOperation(value = "角色列表(不分页)")

    @GetMapping(value = "/all")
    public ResponseEntity<List<PriRoleBean>> all(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap) {
        List<PriRoleBean> resultList = userRoleService.loadRole(formMap);
        return new ResponseEntity<>(resultList, HttpStatus.OK);
    }

}
